#include <iostream>
#include <queue>
#include <cstring>
#include <utility>
using namespace std;
typedef pair<int, int> PII;
const int N = 100;
int n, m;
int g[N][N], d[N][N];
queue<PII> q;
int bfs(PII start)
{
    q.push(start);
    d[start.first][start.second] = 0;
    // 上下左右
    int di[4]{-1, 1, 0, 0}, dj[4]{0, 0, -1, 1};
    while (!q.empty())
    {
        int cur_i = q.front().first;
        int cur_j = q.front().second;
        q.pop();
        // 上下左右可以走的点
        for (int i = 0; i < 4; i++)
        {
            int r = cur_i + di[i];
            int c = cur_j + dj[i];
            if (r >= 0 && r < n && c >= 0 && c < m && g[r][c] != 1 && d[r][c] == -1)
            {
                d[r][c] = d[cur_i][cur_j] + 1;
                q.push({r, c});
            }
        }
    }
    return d[n - 1][m - 1];
}
int main()
{
    //-1 表示没有走过
    memset(d, -1, sizeof d);
    cin >> n >> m;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            cin >> g[i][j];
        }
    }
    cout << bfs({0, 0});
    return 0;
}